/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Buscador;

import Buscador.crawler.Spider;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 *
 * @author usuario_local
 */




public class GenerarMatriz {

    private boolean[][] matrix;
    private int nPag;
    private int topCrawl;
    private HashMap<String, Integer> hm;
    private String[] urls;

    public GenerarMatriz(){
        matrix = new boolean[Spider.maxPag][Spider.maxPag];
        hm = new HashMap<String, Integer>(Spider.maxPag*Spider.maxPag);
        urls = new String[Spider.maxPag];
        topCrawl = 1;
        nPag = 0;


    }

    public int addPagina(String url, String[] refs){
        int indice = getIndice(url);
        
        if (indice < Spider.maxPag) {

            for (int i = 0; i < refs.length; i++) {
                int ind2 = getIndice(refs[i]);
                if (ind2 <Spider.maxPag)
                    matrix[indice][ind2] = true;
            }
            return indice;
        }
        return -1;
    }

    public int getIndice(String url){
        if (hm.containsKey(url)){
            return hm.get(url);
        } else if (nPag < Spider.maxPag){

            hm.put(url, nPag);
            urls[nPag] = url;
            nPag++;
          

            return nPag -1;
        } else{
            //System.err.println("ERROR");
            return 9999999;
        }

    }

    public void generarFicheroNPag(String fich) throws IOException {
        
        PrintWriter pw = new PrintWriter(new FileWriter(fich));
        /*Iterator<Entry<String, Integer> > iter = hm.entrySet().iterator();
        while (iter.hasNext()){
            Entry<String, Integer> e = iter.next();
            pw.println(e.getValue() + " "+ e.getKey());
        }*/

         for (int i = 0; i < nPag; i++) {
            pw.println((i+1) + " " + urls[i]);
        }

        pw.flush();
        pw.close();
    }

    public void generarMatrizAdy(String fich) throws IOException{
        PrintWriter pw = new PrintWriter(new FileWriter(fich));
        for (int i = 0; i < nPag; i++) {
            String st = new String();
            for (int j = 0; j < nPag; j++) {
                if (matrix[i][j]){
                    st = st + "1 ";
                } else{
                    st = st + "0 ";
                }
            }
            pw.println(st);
        }
        pw.flush();
        pw.close();
    }


    public String getNuevaPagina(){
        if (topCrawl < nPag){
            String str = urls[topCrawl];
            topCrawl++;
            return str;
        } else{
            return null; 
        }
    }


}



